package org.bitmaps.cutBitmap
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.utils.ByteArray;
	
	import org.bitmaps.cutBitmap.view.CutPanel;
	import org.bitmaps.event.BmpEvent;
	
	/**
	 * 截图管理类
	 * @author anjue
	 */
	public class CutBitmapManager
	{
		private static var _source:Stage;
		private static var _container:Sprite;
		
		private static var cutPanel:CutPanel;
		private static var _comFun:Function;
		private static var _exitFun:Function;
		public function CutBitmapManager()
		{
		}
		
		/**
		 * 显示截图面板
		 * @param $source        截图面板父级容器
		 * @param $cutComplete   截图完成回调函数
		 * @param $cutExit		 截图退出回调函数
		 */
		public static function show($source:Stage,$cutComplete:Function=null,$cutExit:Function=null):void
		{
			_source = $source;
			_comFun = $cutComplete;
			_exitFun = $cutExit;
			var bmd:BitmapData = new BitmapData(_source.stageWidth,_source.stageHeight,true,0);
			bmd.draw(_source);
			var bmp:Bitmap = new Bitmap(bmd);
			_container = new Sprite();
			_container.addChild(bmp);
			_source.addChild(_container);
			
			cutPanel = new CutPanel(_container);
			cutPanel.addEventListener(CutPanel.CUT_EXIT,cutExit);
			cutPanel.addEventListener(CutPanel.CUT_COMPLETE,cutComplete);
			cutPanel.x = cutPanel.y = 200;
			_container.addChild(cutPanel);
		}
		
		private static function cutExit(e:Event):void
		{
			if(_exitFun!=null)
			{
				_exitFun();
			}
			hide();
		}
		
		private static function cutComplete(e:BmpEvent):void
		{
			var by:ByteArray = e.data as ByteArray;
			if(_comFun!=null)
			{
				_comFun(by);
			}
			hide();
		}
		
		public static function hide():void
		{
			cutPanel.removeEventListener(CutPanel.CUT_COMPLETE,cutComplete);
			cutPanel.removeEventListener(CutPanel.CUT_EXIT,cutExit);
			cutPanel.destroy();
			_source.removeChild(_container);
			_comFun = null;
			_exitFun = null;
		}
	}
}